import { useEffect, useState } from 'react';
import { createId } from 'lib/createId';
import { useUpdate } from './useUpdate';
import { Toast, Modal } from 'antd-mobile';

export const useTags = () => {
  const [tags, setTags] = useState<{ id: number; name: string }[]>([]);
  useEffect(() => {
    let localTags = JSON.parse(window.localStorage.getItem('tags') || '[]');
    if (localTags.length === 0) {
      localTags = [
        { id: createId(), name: '衣' },
        { id: createId(), name: '食' },
        { id: createId(), name: '住' },
        { id: createId(), name: '行' },
      ];
    }
    setTags(localTags);
  }, []);
  useUpdate(() => {
    window.localStorage.setItem('tags', JSON.stringify(tags));
  }, tags);

  const findTag = (id: number) => tags.filter(tag => tag.id === id)[0];
  const findTagIndex = (id: number) => {
    let result = -1;
    for (let i = 0; i < tags.length; i++) {
      if (tags[i].id === id) {
        result = i;
        break;
      }
    }
    return result;
  };
  const updateTag = (id: number, { name }: { name: string }) => {
    setTags(tags.map(tag => (tag.id === id ? { id, name } : tag)));
  };
  const deleteTag = (id: number) => {
    setTags(tags.filter(tag => tag.id !== id));
  };
  const addTag = () => {
    Modal.prompt(
      '请输入新标签名称',
      '',
      [
        {
          text: '取消',
          onPress: value =>
            new Promise(resolve => {
              resolve(value); // 这里执行 resolve 是关闭
            }),
        },
        {
          text: '确定',
          onPress: tagName =>
            new Promise((resolve, reject) => {
              tagName = tagName.trim();
              if (tagName === '') {
                Toast.info('标签名不能为空', 2);
                reject();
                return;
              }
              if (tagName.length > 4) {
                Toast.info('长度不能超过4个字符', 2);
                reject();
                return;
              }
              if (tags.findIndex(tag => tag.name === tagName) !== -1) {
                Toast.info('标签已存在', 2);
                reject();
                return;
              }
              setTags([...tags, { id: createId(), name: tagName }]);
              resolve(tagName);
              Toast.info('添加成功', 2);
            }),
        },
      ],
      'default',
      '',
      ['标签名称']
    );
  };
  const getName = (id: number) => {
    const tag = tags.filter(t => t.id === id)[0];
    return tag ? tag.name : '';
  };
  return {
    tags,
    setTags,
    findTag,
    updateTag,
    findTagIndex,
    deleteTag,
    addTag,
    getName,
  };
};
